package org.gw.ylc.authorization;

import org.gw.ylc.base.context.RequestContext;
import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.model.UserInfo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

public class ContextInterceptor extends HandlerInterceptorAdapter implements InitializingBean {
	@Autowired
	private List<RequestMappingHandlerAdapter> requestMappingHandlerAdapters;

	public void setAuthMode(String authMode) {
	}

	public ContextInterceptor() {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		RequestContext context = new RequestContext();
		context.setPageRequest(buildPageRequest(request));
		context.setUser(UserInfo.ANONYMOUS);
		RequestContextHolder.set(context);
		return true;
	}

	private PageRequest buildPageRequest(HttpServletRequest request) {
		String pageNumber = request.getParameter("pageNumber");
		String pageSize = request.getParameter("pageSize");
		int pN = 0;
		int pS = 15;
		if (StringUtils.hasText(pageNumber)) {
			pN = Integer.parseInt(pageNumber);
		}
		if (StringUtils.hasText(pageSize)) {
			pS = Integer.parseInt(pageSize);
		}
		return new PageRequest(pN, pS);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		RequestContextHolder.remove();
		// ContextParamHolder.removeParams();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		for (RequestMappingHandlerAdapter adapter : requestMappingHandlerAdapters) {
			List<HttpMessageConverter<?>> messageConverters = adapter.getMessageConverters();
			for (HttpMessageConverter<?> c : messageConverters) {
				if (c instanceof StringHttpMessageConverter) {
					StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) c;
					stringHttpMessageConverter.setSupportedMediaTypes(
							Arrays.asList(new MediaType("text", "plain", Charset.forName("utf-8")), MediaType.ALL));
				}
			}

		}
	}

}
